#include "AbstractFactory.h"
#include "AppBase.h"
#include "SessionInit.h"
#include <boost/asio/spawn.hpp>
#include <iostream>

using namespace UTILS;

SessionInit::SessionInit(SerializaReadWritePtr sock) : m_ReadWriteMgr_(sock) {}

void SessionInit::start() {
  auto self(shared_from_this());
  m_ReadWriteMgr_->async_read(
      m_RPCData_, [self](const boost::system::error_code &ec) {
        if (ec) {
          std::cerr << "SessionInit read fail, ec: " << ec << std::endl;
        } else {
          self->handle_read();
        }
      });
}

void SessionInit::stop() { m_ReadWriteMgr_->socket().close(); }

void SessionInit::handle_read() {
  for (uint32_t i = 0; i < m_RPCData_.size(); ++i) {
    std::shared_ptr<AppBase> appPtr =
        APPFactory(AbstractFactory::FactoryType::TCP_SERVER_APP)
            .getObject<AppBase>(m_RPCData_[i].code, m_RPCData_[i].data);
    appPtr->start(m_ReadWriteMgr_);
  }
}
SessionInit::~SessionInit() {
  std::cout << "##### ~SessionInit #####" << std::endl;
}
